package com.neusoft.bizcore.webauth.secret.userpass;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.auth.common.utils.MD5Util;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.webauth.secret.BizcoreAuthenticationException;
import com.neusoft.bizcore.webauth.secret.WebAuthMicroService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserPassAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private WebAuthMicroService webAuthMicroService;

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        final String username = authentication.getPrincipal().toString();

        final ResultDTO<UserBean> result = this.webAuthMicroService.loadUserByUsername(username);

        final UserBean userBean = result.getData();
        if (null == userBean) {
            UserPassAuthenticationProvider.log.warn("用户[" + username + "]不存在");
            throw new BizcoreAuthenticationException("用户不存在", username);
        }
        if (!userBean.isEnabled()) {
            UserPassAuthenticationProvider.log.warn("用户[" + username + "]已被禁用");
            throw new BizcoreAuthenticationException("用户已被禁用", username);
        }

        final String inputPassword =
                MD5Util.getEncryptedPwd(authentication.getCredentials().toString(),
                        (null == userBean.getSalt() ? "" : userBean.getSalt()).getBytes());

        if (!inputPassword.equalsIgnoreCase(userBean.getPassword())) {
            //if (!this.passwordEncoder.matches(inputPassword, userBean.getPassword())) {
            UserPassAuthenticationProvider.log.error("用户[" + username + "]密码错误");
            throw new BizcoreAuthenticationException("密码错误", username);
        }

        final Collection<? extends GrantedAuthority> authorities = userBean.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getRole())).collect(Collectors.toSet());

        final UserPassAuthenticationToken token = new UserPassAuthenticationToken(
                userBean, authentication.getCredentials(),
                authorities);
        token.setDetails(authentication.getDetails());

        return token;
    }

    @Override
    public boolean supports(final Class<?> authentication) {
        return (UserPassAuthenticationToken.class
                .isAssignableFrom(authentication));
    }

}
